package com.yunxun.amqp;

import com.rabbitmq.client.*;
import com.yunxun.utils.ChannelUtil;

import java.io.IOException;
import java.util.HashMap;

public class RPCServer {
    public void receive(String routingKey,String queueName,String exchangeName,String replayToName,String message){
        Channel channel = ChannelUtil.getChannel("Cnbeta服务端");
        try {
            channel.queueDeclare(queueName, true, false, false, new HashMap<>());
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, new HashMap<>());
            channel.basicConsume(queueName, true, "Cnbeta服务端", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String replyTo = properties.getReplyTo();
                    String correlationId = properties.getCorrelationId();
//                    System.out.println("----------收到RPC调用请求消息----------");
//                    System.out.println(consumerTag);
//                    System.out.println("消息属性为:" + properties);
//                    System.out.println("消息内容为" + new String(body));
                      String message = new String(body);
                    try {
                        String orderId = new RPCMethod().addOrder(message);
                        System.err.println(orderId);
                        AMQP.BasicProperties replyProperties = new AMQP.BasicProperties().builder().deliveryMode(2).contentType("UTF-8").correlationId(correlationId).build();
                        channel.basicPublish("", replyTo, replyProperties, orderId.getBytes());
                        System.out.println("----------RPC调用成功 结果已返回----------");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
